
import collections
import pandas as pd
import csv
import pytesseract
from PIL import Image
import numpy as np
import matplotlib.pylab as plt
from matplotlib.ticker import MultipleLocator
from matplotlib.ticker import FormatStrFormatter
from sklearn.linear_model import LinearRegression 
from constant import type_dict_import
from matplotlib.font_manager import FontProperties
font_set = FontProperties(fname=r'C:\windows\fonts\simsun.ttc',size=12)
font_set_2 = FontProperties(fname=r'C:\windows\fonts\simsun.ttc',size=8,weight ="bold")
from settings import tri_manual,bi_manual,loc,cluster_dict


import os

def read_csv(file_path):
    with open(file_path,encoding="utf-8") as f:
        csv_reader = csv.reader(f)
        tb = []
        E = []
        type_dict = collections.defaultdict(list)
        for ri,row in enumerate(csv_reader):
            if ri == 0:
                continue
            tb.append(float(row[0]))
            E.append(float(row[1]))

            row_total = sum([float(i) for i in row[2:]])
            for i,num in enumerate(row[2:]):
                type_dict[i+1].append(float(num)/row_total)
    
    
    tb = np.array(tb)
    E = np.array(E)
    for i in type_dict[i]:
        type_dict[i] = np.array(type_dict[i])

    tb = tb - 0.5/2   #调整到各"自中心点
    E = E - (5.893*1.8099*0.5)/2
    
    
    if min(E)>-5.893*1.8099/2 *5:
        a = -5.893*1.8099/2 *5 
    elif min(E)>-5.893*1.8099/2 *25:
        a = -5.893*1.8099/2 *25
    else:
        a = -5.893*1.8099/2 *35
    if max(E) <= 5.893*1.8099/2 *5 :
        if min(E)>-5.893*1.8099/2 *25:
            a = -5.893*1.8099/2 *25
        else:
            a = -5.893*1.8099/2 *35
        b = 5.893*1.8099/2 *5
        sign_loc = 'lower right'
    elif max(E) < 5.893*1.8099/2 *35:
        b = 5.893*1.8099/2 *35
        sign_loc = loc
    elif  max(E) < 5.893*1.8099/2 *75:
        b = 5.893*1.8099/2 *75
        sign_loc = loc
    elif  max(E) < 5.893*1.8099/2 *115:
        b = 5.893*1.8099/2 *115
        sign_loc = loc
    elif max(E) < 5.893*1.8099/2 *175:
        b = 5.893*1.8099/2 *175
        sign_loc = loc
    return tb,E,type_dict, (a,b),round((b-a)/(5.893*1.8099/2)/10),sign_loc
    a = """   
    if max(E)-min(E) <= 5.893*1.8099*20:
        a = min(E) - 5.893*1.8099*10+(max(E)-min(E))/2    
        b = max(E) + 5.893*1.8099*10-(max(E)-min(E))/2
        a = a - a%(5.893*1.8099/2) - (5.893*1.8099/2)
        b = b - b%(5.893*1.8099/2) + (5.893*1.8099/2)
        return tb,E,type_dict, (a,b),2
    else:
        slim = int((max(E)-min(E))/(5.893*1.8099*10))
        return tb,E,type_dict, (min(E)-(5.893*1.8099*10),max(E)+(5.893*1.8099*10)),slim+2"""
     
                       
class LatticeImage:
    def __init__(self,csv_path,title,tb_ratio):
        self.color = ["y",'r','darkorchid','g','b','fuchsia','limegreen','lightseagreen','chocolate','deepskyblue','y','#990033','#FF9966','#996699','#FF99CC','#999900','#50616d']
        self.color_dict = {
            "森林" :"#0000FF",
            "高山植被" :"#32cd32",
            "沼泽" :"#804000",
            "草丛" :"#FFA500",
            "灌丛" :"#007f00",
            "草原" :"#DC143C",
            "草甸" :"#800080",
            "荒漠" :"#ff00ff",
            }
        self.title = title
        self.markerstyle = '.'
        self.tb,self.E,self.type_dict,y_range,yy ,self.sign_loc= read_csv(csv_path)
        self.type_num = max(self.type_dict.keys())
        self.TB_max,self.TB_min,self.E_max,self.E_min = max(self.tb),min(self.tb),max(self.E),min(self.E)
        self.yy = yy
        self.fig= plt.subplots(figsize=(12,yy*2))
        self.ax = plt.gca()
        self.ax.xaxis.set_ticks_position('bottom')
        self.ax.spines['bottom'].set_position(('data', 0))
        self.ax.yaxis.set_ticks_position('left')
        self.ax.spines['left'].set_position(('data', 0))
        self.ax.spines['right'].set_color('none')
        self.ax.spines['top'].set_color('none')
        
        
        poly_text2 = '分区界限'
        for i in [1.5,3,6,10,14,22]:
            self.ax.axvline(x=i,ls="--",c="#000000",linewidth=1,alpha = 0.5)
            
        self.ax.xaxis.set_ticks([1.5,3,6,10,14,22,30])  
        self.ax.plot(np.linspace(0, 30, 1000000), 4*5.893*1.8099*np.linspace(0, 30, 1000000), '--k',linewidth=1,label=poly_text2,alpha = 0.5)
        self.ax.plot(np.linspace(0, 30, 1000000), 2*5.893*1.8099*np.linspace(0, 30, 1000000), '--k',linewidth=1,alpha = 0.5)
        self.ax.plot(np.linspace(0, 30, 1000000), 5.893*1.8099*np.linspace(0, 30, 1000000), '--k', linewidth=1,alpha = 0.5)
        self.ax.plot(np.linspace(0, 30, 1000000), (1/3)*5.893*1.8099*np.linspace(0, 30, 1000000), '--k',linewidth=1,alpha = 0.5)
        #3.4修改： 删除p/pe=3线 self.ax.plot(np.linspace(0, 30, 1000000), (-1/3)*5.893*1.8099*np.linspace(0, 30, 1000000), '--k',linewidth=1,alpha = 0.5)
        self.ax.plot(np.linspace(0, 30, 1000000), (-1/3)*5.893*1.8099*np.linspace(0, 30, 1000000), '--k',linewidth=1,alpha = 0.5)    
        self.ax.plot(np.linspace(0, 30, 1000000), -0.5*5.893*1.8099*np.linspace(0, 30, 1000000), '--k',linewidth=1,alpha = 0.5)
        self.ax.plot(np.linspace(0, 30, 1000000), (-3/5)*5.893*1.8099*np.linspace(0, 30, 1000000), '--k',linewidth=1,alpha = 0.5)
        self.ax.plot(np.linspace(0, 30, 1000000), (-2/3)*5.893*1.8099*np.linspace(0, 30, 1000000), '--k',linewidth=1,alpha = 0.5)
        self.ax.plot(np.linspace(0, 30, 1000000), -5.893*1.8099*np.linspace(0, 30, 1000000), '--k',linewidth=1,alpha = 0.5)
        
        
        plt.axhline(0, color='k')#第四区线，p=1/2pe
        plt.axhline(0, color='k')#

        self.ax.xaxis.grid(True, which='minor',linestyle='--', linewidth=0.5,alpha=0.3)
        self.ax.xaxis.grid(True,linestyle='--', linewidth=0.5,alpha=0.3)
        self.ax.yaxis.grid(True, which='minor',linestyle='--', linewidth=0.5,alpha=0.3)
        self.ax.yaxis.grid(True,linestyle='--', linewidth=0.5,alpha=0.3)
        self.ax.set_xlabel('TB (℃)',fontproperties =font_set)
        self.ax.set_ylabel('E',fontproperties =font_set)
        
        self.ax.xaxis.set_major_locator(MultipleLocator(5))
        self.ax.yaxis.set_major_locator(MultipleLocator(5.893*1.8099*0.5*10))
        self.ax.xaxis.set_major_formatter(FormatStrFormatter('%d'))
        self.ax.yaxis.set_major_formatter(FormatStrFormatter('%1.1f'))
        self.ax.xaxis.set_minor_locator(MultipleLocator(0.5))
        self.ax.yaxis.set_minor_locator(MultipleLocator(5.893*1.8099*0.5))
        self.ax.set_xlim(0,30.0)  #设置坐标取值范围
        self.ax.set_ylim(y_range)
        plt.draw()
        self.y_ticks = [float(i.get_text()) for i in self.ax.yaxis.get_ticklabels()]
        
        y_range = (self.y_ticks[0],self.y_ticks[-1])
        
        k = self.y_ticks[-1]/30
        k_ = self.y_ticks[0]/30
        
        if k < (4*5.893*1.8099):
            plt.text(y_range[1]/(4*5.893*1.8099)-1,y_range[1]+3,"pe/p=0.25",fontproperties = font_set)
        else:
            plt.text(30,30*(4*5.893*1.8099),"pe/p=0.25",fontproperties = font_set)
            
        if k < (2*5.893*1.8099):
            plt.text(y_range[1]/(2*5.893*1.8099)-1,y_range[1]+3,"pe/p=0.5",fontproperties = font_set)
        else:
            plt.text(30,30*(2*5.893*1.8099),"pe/p=0.5",fontproperties = font_set)
            
        if k < (5.893*1.8099):
            plt.text(y_range[1]/(5.893*1.8099)-0.7,y_range[1]+3,"pe/p=1",fontproperties = font_set)
        else:
            plt.text(30,30*(5.893*1.8099),"pe/p=1",fontproperties = font_set)
            
        if k < (1/3)*5.893*1.8099:
            plt.text(y_range[1]/((1/3)*5.893*1.8099)-1,y_range[1]+3,"pe/p=1.5",fontproperties = font_set)
        else:
            plt.text(30,30*((1/3)*5.893*1.8099),"pe/p=1.5",fontproperties = font_set)     
            
        plt.text(30,0,"pe/p=2",fontproperties = font_set)
        
        #3.4修改： 删除p/pe=3线
        #if k_ > (-1/3)*5.893*1.8099:
          #  plt.text(y_range[0]/((-1/3)*5.893*1.8099)-0.7,y_range[0]-6,"pe/p=3",fontproperties = font_set)
        #else:
         #   plt.text(30,30*((-1/3)*5.893*1.8099),"pe/p=3",fontproperties = font_set)     
        if k_ > -(1/3)*5.893*1.8099:
            plt.text(y_range[0]/(-(1/3)*5.893*1.8099)-0.7,y_range[0]-6,"pe/p=3",fontproperties = font_set)
        else:
            plt.text(30,30*(-(1/3)*5.893*1.8099),"pe/p=3",fontproperties = font_set)        
        if k_ > -0.5*5.893*1.8099:
            plt.text(y_range[0]/(-0.5*5.893*1.8099)-0.3,y_range[0]-6,"pe/p=4",fontproperties = font_set)
        else:
            plt.text(30,30*(-0.5*5.893*1.8099),"pe/p=4",fontproperties = font_set)     
        if k_ > -(3/5)*5.893*1.8099:
            plt.text(y_range[0]/(-(3/5)*5.893*1.8099)-0.4,y_range[0]-6,"pe/p=5",fontproperties = font_set)
        else:
            plt.text(30,30*(-(3/5)*5.893*1.8099),"pe/p=5",fontproperties = font_set)        
        if k_ > -(2/3)*5.893*1.8099:
            plt.text(y_range[0]/(-(4/5)*5.893*1.8099)-0.5,y_range[0]-6,"pe/p=6",fontproperties = font_set)
        else:
            plt.text(30,30*(-(2/3)*5.893*1.8099),"pe/p=6",fontproperties = font_set)        

        if k_ > -5.893*1.8099:
            plt.text(y_range[0]/(-5.893*1.8099)-0.5,y_range[0]-6,"p=0",fontproperties = font_set)
        else:
            plt.text(30,30*(-5.893*1.8099),"p=0",fontproperties = font_set)     

        ###划分界限的标签
        ###划百分比
        point_set = [(0.5*i,round(j*(5.893*1.8099*0.5),8)) for j in range(int(y_range[0]/(5.893*1.8099*0.5)),int(y_range[1]/(5.893*1.8099*0.5))) for i in range(0,60)]
        tb_e = [(self.tb[i]-0.25,round(self.E[i]-(5.893*1.8099*0.5)/2,8)) for i in range(len(self.tb))]
        valid_point_set = list(set(point_set) - set(tb_e))
        self.q = point_set
        self.p = tb_e
        area_dict = {}
        area_dict_default = {}
        
        for i in range(12):
            for j in range(7):
                area_dict[(i,j)] = []
                area_dict_default[(i,j)] = []
        area_dict_default[(5,0)] = [[5.5,1]]     
        for xy in point_set :
            x,y = xy[0],xy[1]
            if y>  4*5.893*1.8099* x: a = 0
            elif y>  2*5.893*1.8099* x: a = 1
            elif y >  5.893*1.8099* x: a = 2
            elif y >  (1/3)*5.893*1.8099* x : a = 3    
            elif y >= 0: a = 4
            elif y >  -(1/3)*5.893*1.8099* x : a = 5
            elif y >=  -0.5*5.893*1.8099* x: a = 6
            elif y >  -(3/5)*5.893*1.8099* x : a = 7  
            elif y >  -(2/3)*5.893*1.8099* x : a = 8  
            elif y >=  -5.893*1.8099* x: a = 9
            else : a = 10
                
                
            if x <1.5: b = 0
            elif x<3: b = 1
            elif x<6: b = 2
            elif x<10: b = 3
            elif x<14: b = 4
            elif x<22: b = 5
            elif x<30: b = 6
            area_dict_default[(a,b)].append(xy)
                
        for xy in valid_point_set :
            x,y = xy[0],xy[1]
            if y>  4*5.893*1.8099* x: a = 0
            elif y>  2*5.893*1.8099* x: a = 1
            elif y >  5.893*1.8099* x: a = 2
            elif y >  (1/3)*5.893*1.8099* x : a = 3    
            elif y >= 0: a = 4
            elif y >  -(1/3)*5.893*1.8099* x : a = 5
            elif y >=  -0.5*5.893*1.8099* x: a = 6
            elif y >  -(3/5)*5.893*1.8099* x : a = 7  
            elif y >  -(2/3)*5.893*1.8099* x : a = 8  
            elif y >=  -5.893*1.8099* x: a = 9
            else : a = 10
                
                
            if x <1.5: b = 0
            elif x<3: b = 1
            elif x<6: b = 2
            elif x<10: b = 3
            elif x<14: b = 4
            elif x<22: b = 5
            elif x<30: b = 6
            area_dict[(a,b)].append(xy)
        self.r3 = tb_ratio
        self.r4 = area_dict
        self.r5 = area_dict_default
        def get_text_location(x,y):
            point_list = area_dict[(x,y)]
            if not point_list:
                point_list = area_dict_default[(x,y)]
                return sum([i[0] for i in point_list])/len(point_list),sum([i[1] for i in point_list])/len(point_list)
            mean_x = sum([i[0] for i in point_list])/len(point_list)
            mean_y = sum([i[1] for i in point_list])/len(point_list)
            point_list.sort(key = lambda x : (x[0] - mean_x)**2 + (x[1] - mean_y)**2 )
            for i in point_list:
                if (i[0]+0.5,i[1]) in point_list:
                    return i[0],i[1]

            point_list = area_dict_default[(x,y)]
            return sum([i[0] for i in point_list])/len(point_list),sum([i[1] for i in point_list])/len(point_list)
            
        
        for i in range(12):
            for j in range(7):
                if tb_ratio[i][j] != 0 :
                    #for e in area_dict[(i,j)]:
                       # plt.text(e[0],e[1],str(10*i+j),fontproperties = font_set_2)
                    x,y = get_text_location(i,j)
                    plt.text(x,y,"%.2f"%(tb_ratio[i][j]*100) +"%",fontproperties = font_set_2)
        
        
        self.name_dict = {'0': ['森林', 0], '1': ['灌丛', 1], '2': ['草丛', 2], '3': ['草原', 3], '4': ['荒漠', 4], '5': ['草甸', 5], '6': ['沼泽', 6], '7': ['高山植被', 7], '8': ['栽培植被', 8]}
        
           
    def set_color_and_mark(self,color_dict = dict , mark = "." ):
        self.color_dict = color_dict 
        self.markerstyle = mark
        

    def get_xy(self,columns):
        index_dict = collections.defaultdict(list)
        type_dict_final = type_dict_import
        type_index_list = [[] for i in range(9)]
        for num,i in enumerate(columns[2:]):
            type_index_list[type_dict_final[str(int(i))]] .append(num)

        new_type_dict = {}
        for i in range(1,10):
            new_type_dict[i] = [sum([self.type_dict[index+1][j] for index in type_index_list[i-1]]) for j in range(len(self.type_dict[1]))]

        self.type_dict  = new_type_dict 
        columns = ["","",] + [str(i+1) for i in range(9)]
        for i in range(1,10):
            for index,ratio in enumerate(self.type_dict[i]):
                if not index_dict[(self.tb[index],self.E[index])]:
                    index_dict[(self.tb[index],self.E[index])] = [[],[],[]]

                if ratio >= 0.6321:
                    index_dict[(self.tb[index],self.E[index])][0].append(str(columns[i+1]))
                elif ratio >= 0.3679:
                    index_dict[(self.tb[index],self.E[index])][1].append(str(columns[i+1]))
                else:
                    index_dict[(self.tb[index],self.E[index])][2].append(str(columns[i+1]))

        return index_dict
    
    
    def generate_image(self,save_path,columns,line_list,csv_df,ii,area,max_limit,iscluster,temp_sign):  
        ii = int(ii)
        writel = line_list["writel"] 
 
        line_list = line_list["k_list"] 
        index_dict = self.get_xy(columns)
        write_dict = collections.defaultdict(list)
        for i in index_dict:
            if index_dict[i][0]:
                write_dict[(tuple(set(index_dict[i][0])),tuple(set(index_dict[i][2])),0)].append(i)
            else:
                write_dict[(tuple(set(index_dict[i][1])),tuple(set(index_dict[i][2])),1)].append(i)
        columns = ["","",] + [str(i+1) for i in range(9)]

   
        x = np.linspace(0,max_limit,100)    
        if not iscluster:
            for index,i in enumerate(line_list):
                k,b,r2,typei = i["k"],i["b"],i["r"],i["type"]
                if typei == "none":
                        pass
                elif typei == "vertical":
                    if b:
                        print(b)
                        plt.vlines(k,0,b,colors=self.color[ii], label = "TB=%.2f"%k,linewidth=0.6 )
                    else:
                        print(2)
                        plt.axvline(x=k ,c=self.color[ii], label = "TB=%.2f"%k,linewidth=0.6 )
                elif typei == "horizon":
                        x = np.linspace(writel[index][0],writel[index][1],100)   
                        plt.plot(x,k*x+b ,c=self.color[ii],label = "E=%.2f"%b,linewidth=0.6 )
                else:
                    x = np.linspace(writel[index][0],writel[index][1],100)    
                    plt.plot(x,k*x+b , c=self.color[ii],label = "E=%.2f*TB+%.2f(R²=%.2f)"%(k,b,r2),linewidth=0.6 )
                

        #self.ax.plot(np.mean(csv_nif.tb),np.mean(csv_df.E_sum),"o",markersize =1,alpha = 1,c="#000000",label = "均值点")
        self.ax.axvline(x=np.mean(csv_df.tb),ls="--",c="r",linewidth=0.5,alpha = 0.5)
        self.ax.axhline(y=np.mean(csv_df.E_sum),ls="--",c="r",linewidth=0.5,alpha = 0.5)
        
        ticks = [0,1.5,3,6,10,14,22,30]
        
        self.ax.xaxis.set_ticks(sorted(ticks+ [np.mean(csv_df.tb)]))
        self.ax.xaxis.set_ticklabels(sorted(ticks +[round(float(np.mean(csv_df.tb)),2)]))
        
        red_x = sorted(ticks+ [round(float(np.mean(csv_df.tb)),2)]).index(round(float(np.mean(csv_df.tb)),2))
        self.ax.xaxis.get_ticklabels()[red_x].set_color("red")
        self.ax.xaxis.get_ticklabels()[red_x].set_alpha(0)
        #画线 y范围变动 没写完
        ticks = self.y_ticks
        is_delete_y_label = -1
        if is_delete_y_label >= 0:
            ticks[is_delete_y_label] = round(float(np.mean(csv_df.E_sum)),2)
            self.ax.yaxis.set_ticks(ticks)
            self.ax.yaxis.set_ticklabels(ticks)
            red_y = ticks.index(round(float(np.mean(csv_df.E_sum)),2))
        else:
            self.ax.yaxis.set_ticks(sorted(ticks+ [np.mean(csv_df.E_sum)]))
            ticks =  sorted(ticks +[round(float(np.mean(csv_df.E_sum)),2)])
            ticklabels = ticks
            self.ax.yaxis.set_ticklabels(ticklabels)
            red_y = ticks.index(round(float(np.mean(csv_df.E_sum)),2))
        
        self.ax.yaxis.get_ticklabels()[red_y].set_color("red")
        self.ax.yaxis.get_ticklabels()[red_y].set_alpha(0)

        plt.legend(prop = font_set,loc = loc)
        
        temp_store_index = []
        for key in write_dict:
            if not key[2]:
                temp_store_index.append(key)
        temp_store_index.sort(key = lambda x: x[0])    
        
        for key in temp_store_index:
            priority = [self.name_dict[str(int(i)-1)] for i in key[0]]
            priority.sort(key = lambda x : x[1])
            priority = [i[0] for i in priority] 
            
            color = self.color_dict[priority[0]]
            
            if key[1]:
                crisscross = [self.name_dict[str(int(i)-1)] for i in key[1]]
                crisscross.sort(key = lambda x : x[1])
                crisscross = [i[0] for i in crisscross]
                label = "稳态：  " + ",".join(i for i in priority)# + "\n混沌态：" + ",".join(i for i in crisscross if i != "栽培植被")
            else:
                label = "稳态：  " + ",".join(i for i in priority)
            self.ax.plot([i[0] for i in write_dict[key]],[i[1] for i in write_dict[key]], ".", markerfacecolor='none',color=color, markersize = 12,label=label,markeredgecolor=color,markeredgewidth=0.8)
            plt.legend(prop = font_set,loc = loc)    
   


        temp_store_index = []    
        for key in write_dict:
            if key[2] and key[0]: 
                temp_store_index.append(key)
        temp_store_index.sort(key = lambda x: x[0])            

        for key in temp_store_index:     
            if len(key[0]) == 1:
                
                priority = [self.name_dict[str(int(i)-1)] for i in key[0]]
                priority.sort(key = lambda x : x[1])
                priority = [i[0] for i in priority]
                color = self.color_dict[priority[0]]
                if key[1]:
                    crisscross = [self.name_dict[str(int(i)-1)] for i in key[1]]
                    crisscross.sort(key = lambda x : x[1])
                    crisscross = [i[0] for i in crisscross]
                    label = "亚稳态：" + ",".join(i for i in priority) #+ "\n混沌态：" +",".join(i for i in crisscross if i != "栽培植被")
                else:
                    label = "亚稳态：" + ",".join(i for i in priority)
                #label = ",".join(self.name_dict[i] for i in key[0]) +"为优势，和" + ",".join(self.name_dict[i] for i in key[1]) +"的交错类型"
                #pattern = re.compile('.{30}')
                #label = '\n'.join(pattern.findall(label)) + "\n" + label[-(len(label)%30):]
                self.ax.plot([i[0] for i in write_dict[key]],[i[1] for i in write_dict[key]], "^", color=color, markerfacecolor='none',markersize = 6,label=label,markeredgecolor=color,markeredgewidth=0.8)
                plt.legend(prop = font_set,loc = loc)

                
        for key in temp_store_index:     
            if len(key[0]) == 2:
                priority = [self.name_dict[str(int(i)-1)] for i in key[0]]
                priority.sort(key = lambda x : x[1])
                priority = [i[0] for i in priority]
                color = self.color_dict[priority[0]]
                if key[1]:
                    
                    crisscross = [self.name_dict[str(int(i)-1)] for i in key[1]]
                    crisscross.sort(key = lambda x : x[1])
                    crisscross = [i[0] for i in crisscross]
                    label = "亚稳态：" + ",".join(i for i in priority) #+ "\n混沌态：" +",".join(i for i in crisscross if i != "栽培植被")
                else:
                    label = "亚稳态：" + ",".join(i for i in priority)
                #label = ",".join(self.name_dict[i] for i in key[0]) +"为优势，和" + ",".join(self.name_dict[i] for i in key[1]) +"的交错类型"
                #pattern = re.compile('.{30}')
                #label = '\n'.join(pattern.findall(label)) + "\n" + label[-(len(label)%30):]
                self.ax.plot([i[0] for i in write_dict[key]],[i[1] for i in write_dict[key]], "s", color=color, markerfacecolor='none',markersize = 6,label=label,markeredgecolor=color,markeredgewidth=0.8)
                plt.legend(prop = font_set,loc = loc)

        
        temp_store_index = []   
        for key in write_dict:
            if key[2] and not key[0] and key[1]:
                temp_store_index.append(key)
        temp_store_index.sort(key = lambda x: x[1])            
        for key in temp_store_index:     

            crisscross = [self.name_dict[str(int(i)-1)] for i in key[1]]
            crisscross.sort(key = lambda x : x[1])
            crisscross = [i[0] for i in crisscross]

            color = self.color_dict[crisscross[0]]
            label = "混沌态" #+ ",".join(i for i in crisscross if i != "栽培植被")
            #pattern = re.compile('.{30}')
            #label = ",".join(self.name_dict[i] for i in key[1]) +"交错类型"
            #label = '\n'.join(pattern.findall(label)) + "\n" + label[-(len(label)%30):]
            self.ax.plot([i[0] for i in write_dict[key]],[i[1] for i in write_dict[key]], "D", markerfacecolor='none',color="#FFFF00", markersize = 4,label=label,markeredgecolor="#FFFF00",markeredgewidth=0.8)
            plt.legend(prop = font_set,loc = loc) 


        self.ax.set_title(self.title.replace("_"," ") + " 地域%s 类型"%area + str(ii) + "\n  ", fontproperties = font_set)
        self.ax.scatter(csv_df.tb,csv_df.E_sum,2,alpha =0.5,c=self.color[ii],zorder=2,label = "类型" + str(ii))
        
        self.ax.scatter(np.mean(csv_df.tb),np.mean(csv_df.E_sum),1,marker = "o",c="#000000",zorder=3,label = "均值点"+"(%s,%s)"%(round(np.mean(csv_df.tb),2),round(np.mean(csv_df.E_sum),2)))
        
        plt.legend(prop = font_set,loc = loc)
        plt.savefig(save_path, dpi = 900,bbox_inches='tight')
        plt.clf()
        plt.close()

class ExecuteCsv_rewrite:
    def __init__(self,csv_file,title,word,save_path,csv_list):
        self.save_path = save_path
        f1=open(csv_file)#############自己修改###########
        df = pd.read_csv(f1)#############自己修改###########
        for i in csv_list:
            f2=open(i)#############自己修改###########
            df2 = pd.read_csv(f2)#############自己修改###########
            df = pd.concat([df,df2])
        count = 0
        df= df.reset_index(drop=True)
        index_dict ={}
        K = len(df['GRID_CODE'].value_counts())
        dataMat = []
        self.max_limit = min(30,int(df["tb"].max())+5)

        for i in range(len(df)):
            if df.GRID_CODE[i] not in index_dict:
                index_dict[ df.GRID_CODE[i]] = count
                count += 1

            x = int((float(df.tb[i])/0.5 + 1))
            if df.E_sum[i] >0 :
                y = int((float(df.E_sum[i])/(5.893*1.8099*0.5) + 1))
            else:
                y = int((float(df.E_sum[i])/(5.893*1.8099*0.5) ))
            x_ret = x*0.5
            y_ret = y*(5.893*1.8099*0.5)
                
            retlist = [x_ret,y_ret] + [0] * K
            retlist[index_dict[df.GRID_CODE[i]]+2] = 1
            dataMat.append(retlist)
                
        df = pd.DataFrame(dataMat)
        self.columns =  ["tb","e_sum"] + list(index_dict.keys())
        df.columns  = self.columns
        self.word = word
        groupedMat = df.groupby([df["tb"],df["e_sum"]]).sum()
        groupedMat.to_csv(self.save_path + "\\" + (title.replace("/","_")) + word[:-1] + "_格子图占比.csv") 
        self.lat_csv = self.save_path + "\\" + (title.replace("/","_")) + self.word[:-1] + "_格子图占比.csv"
    def set_save_path(self,save_path):
        try : 
            os.mkdir(save_path)
        except:
            pass
        self.save_path = save_path
        
    def check_not_valid(self,title,csv_list,area,img_list,max_limit,temp_sign):
        return False
        tmp_split = [0,1.5,3,6,10,14,22,30,100]
        swi = False
        for ii in range(len(csv_list)):
            f5=open(csv_list[ii])#############自己修改###########
            csv_df = pd.read_csv(f5)#############自己修改###########
            
            if temp_sign:
                if not swi and len(csv_df[(csv_df["tb"] < tmp_split[temp_sign]) & (csv_df["tb"] >= tmp_split[temp_sign-1])])/len(csv_df) <0.6321:
                    print("【警告】%s地域%s类型%s的温度带占比不到0.6321"%(title,area,str(ii+1)))
                    swi = True
                elif len(csv_df[(csv_df["tb"] < tmp_split[temp_sign]) & (csv_df["tb"] >= tmp_split[temp_sign-1])])/len(csv_df) <0.6321:
                    print("【警告】%s地域%s类型%s的温度带占比不到0.6321"%(title,area,str(ii+1)))
        return swi
    def start_execute(self,title,csv_list,area,max_limit,temp_sign,k_dict):
        
    
        #for ii in range(len(line_list)):
        for ii in range(len(csv_list)):
            if not k_dict[csv_list[ii].split("\\")[-1]]:continue
            f5=open(csv_list[ii])#############自己修改###########
            df = pd.read_csv(f5)#############自己修改###########
        
        
        #获取各个区比例


            tb_count_list = [[0,0,0,0,0,0,0] for i in range(12)]
            for i in range(len(df)):
                if df.E_sum[i] >  4*5.893*1.8099* df.tb[i]: a = 0 #0.25
                
                elif df.E_sum[i] >  2*5.893*1.8099* df.tb[i]: a = 1 #0.5
                
                elif df.E_sum[i] >  5.893*1.8099* df.tb[i]: a = 2
                elif df.E_sum[i] >  (1/3)*5.893*1.8099* df.tb[i] :a = 3
                elif df.E_sum[i] >= 0: a = 4
                elif df.E_sum[i] >  -(1/3)*5.893*1.8099* df.tb[i] :a = 5
                elif df.E_sum[i] >  -0.5*5.893*1.8099* df.tb[i]: a = 6 #4
                elif df.E_sum[i] >  -(3/5)*5.893*1.8099* df.tb[i] :a = 7 # 5
                elif df.E_sum[i] >  -(2/3)*5.893*1.8099* df.tb[i] :a = 8 # 6
                elif df.E_sum[i] >  -5.893*1.8099* df.tb[i]: a = 9 # p = 0
                else : a = 10


                if df.tb[i] <1.5: b = 0
                elif df.tb[i]<3: b = 1
                elif df.tb[i]<6: b = 2
                elif df.tb[i]<10: b = 3
                elif df.tb[i]<14: b = 4
                elif df.tb[i]<22: b = 5
                elif df.tb[i]<30: b = 6

                tb_count_list[a][b] += 1
            self.tb_ratio = [[i/len(df.tb) for i in tb_count_list[j]] for j in range(12)]    
            f6=open(csv_list[ii])#############自己修改###########
            csv_df = pd.read_csv(f6)#############自己修改###########
           # print("初始化图对象")
            typee = csv_list[ii].split("\\")[-1].split("_")[0].split(".")[3]
            latticeImage = LatticeImage(self.lat_csv,title,self.tb_ratio)


            latticeImage.generate_image(self.save_path + "\\" + (title.replace("/","_")) + "_地域" +str(area)+"_类型"+ str(typee) + ".png",self.columns,k_dict[csv_list[ii].split("\\")[-1]],csv_df,csv_list[ii].split("\\")[-1].split("_")[0].split(".")[3],area,self.max_limit,str(area) in cluster_dict and (not cluster_dict[area] or typee in cluster_dict[area]),temp_sign)


    def got_true_title(self,i = ("","")):
        tempr = ['温度交错带','高山极地带','苔原带','寒温带','中温带','暖温带','亚热带','热带']
        if len(i[0]) == 1:
            return self.title + " " + tempr[int(i[0])] + " 地域" + i[1]
        else:
            return self.title + " " + "-".join(tempr[int(j)] for j in i[0].split(".")) +"交错带" + " 地域" + i[1]
        
        
        
